package com.cn.algorithm02.class07;

import java.util.Comparator;
import java.util.TreeMap;

/***
 * @author: hels
 * @description: 比较器对比   时间复杂度位O(N*logN)
 * 1· TreeMap 通过比较器来进行排序，
 * 2· 当两个对象通过比较器对比相等时，后者不会覆盖
 **/
public class C01_Comparator {
    public static void main(String[] args) {
        Students stu1 = new Students(1, 21, "A");
        Students stu2 = new Students(2, 11, "B");
        Students stu3 = new Students(3, 15, "C");
        Students stu4 = new Students(4, 15, "D");
        // 1 比较器用法
        Comparator<Students> comparator = new Comparator<Students>() {
            @Override
            public int compare(Students o1, Students o2) {
                return o1.age != o2.age ? (o1.age - o2.age) : (- o1.hashCode() + o2.hashCode());
            }
        };

        // lamada 表达式方式
        Comparator<Students> comparator1 = new Comparator<Students>() {
            @Override
            public int compare(Students o1, Students o2) {
                return o1.getId() - o2.getId();
            }
        };
        TreeMap<Students, String> t = new TreeMap<>((a,b) -> b.getId() - a.getId());

        TreeMap<Students, String> t2 = new TreeMap<>(comparator);
        t.put(stu3, "我是" + stu3.name);
        t.put(stu4, "我是" + stu4.name);
        t.put(stu1, "我是" + stu1.name);
        t.put(stu2, "我是" + stu2.name);

        for (Students s : t.keySet()) {
            System.out.println(s);
        }

    }
}
